<template>
  <header class="bg-fff mt-10 ml-10 mr-10">
    <div class>
      <!-- 手机号码 -->
      <div class="handset ml-20 mr-20 pt-20 flex jc-sb pb-5">
        <input v-model="phone" id="phone" class="f14 w100pc" type="text" placeholder="请输入手机号，验证或登录">
      </div>
      <!-- 验证码 -->
      <div class="handset ml-20 mr-20 flex jc-sb mt-20 pb-5">
        <input v-model="smsCode" id="smsCode" class="f14" placeholder="请输入验证码">
        <input
          id="code"
          @click="getSmscode"
          class="f12 bg-or fff pl-20 pr-20"
          type="button"
          :disabled="disabled"
          :value=" value"
        >
      </div>

      <!-- 登录 -->
      <button @click="login" class="butt ml-20 mr-20 f12">取消</button>
      <button @click="login" class="butt ml-20 mr-20 f12">登录</button>
    </div>
  </header>
</template>

<script>
export default {
  data() {
    return {
      phone: "",
      smsCode: "",
      value: "获 取 验 证 码",
      disabled: false
    };
  },
  methods: {
    // 获取验证码
    async getSmscode() {
      if (!this.phone) {
        alert("请输入号码");
        return false;
      }
      var phoneReg = /^1[3456789]\d{9}/;
      if (!phoneReg.test(this.phone)) {
        alert("输入正确的号码");
        return false;
      }

      let sum = 10;
      this.disabled = true;
      let time = setInterval(() => {
        this.value = `获取验证码(${--sum})`;
        if (sum === 0) {
          clearInterval(time);
          this.value = "从新发送";
          this.disabled = false;
        }
      }, 300);

      let isphone = this.phone;
      let url = `/user/getSmsCode?phone=${isphone}`;
      try {
        let res = await this.$axios.post(url);
        // console.log(res);
      } catch (error) {}
    },

    // 登录
    async login() {
      if (!this.smsCode) {
        alert("输入验证码");
        return false;
      }
      let url = "/user/loginBySmsCode";
      let data = {
        phone: this.phone,
        smsCode: this.smsCode
      };
      try {
        let res = await this.$axios.post(url, data);
        // console.log(res);
        this.$store.commit("updateLogin", true);
        this.$store.commit("updateToken", res.data.sessionToken);
        this.$store.commit("updateUsername", this.phone);
        this.$router.go(-1);
        this.$toast.success("登录成功");
      } catch (error) {}
    }
  }
};
</script>

<style lang="less" scoped>
@import "../style/login.less";
</style>

